<?php
require_once('internal/IModule.interface.php');

class Users2 implements IModule {
	public $sections;
	private $email_regex;
	function __construct($engine=null) {
		global $lang;
		// The email filtering regular expression
		//$this->email_regex = '[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2,6})\b';
		$this->email_regex = '^[a-zA-Z](([[:alnum:]._-]+)*)?@([[:alnum:]\-_]+\.)+[a-zA-Z]{2,6}$';
		$this->engine = $engine;
		$this->sections = array($lang['back'] => 'javascript:doBack();');
	}

	function execute() {
		$do = $_GET['do'];
		switch ($do) {
			case 'edit':
				$this->userEdit();
				break;
			case 'add':
				$this->userAdd();
				break;
			case 'delete':
				$this->userDelete();
				break;
			case 'list':
			case '':
				$this->displayList();
				break;
			default:
				echo "<h3>Unknown action</h3>\n";
		}
	}
	/*
	function displayList()
	Displays an interactive list
	*/
	function displayList() {
	global $lang;
	?>
		<div id="user_list">
			<div class="user" id="user_add">
				<div class="icon"><img src="modules/admin/users2/add.png" alt="<?php echo $lang['add']; ?>" /></div>
				<div class="text"><?php echo $lang['add']; ?></div>
			</div>
			<div class="user" id="user_trash">
				<div class="icon"><img src="modules/admin/users2/trash.png" alt="<?php echo $lang['delete']; ?>" /></div>
				<div class="text"><?php echo $lang['delete']; ?></div>
			</div>
		<?php
			// Loading the user list
			$all = $this->fetchMerged();
			$this->writeJsonInfo($all);

			for ($i=0;$i<count($all);$i++) {
				$u = $all[$i];

				// Setting the user's avatar path
				$avpath = 'media/avatars/';
				// Setting the default user avatar if user is inactive or has none
				if ((int)$u['activated']===0) $avatar = $avpath.'inactive.png';
				else $avatar = file_exists($avpath.$u['name'].'.png') ? $avpath.$u['name'].'.png' : $avpath.'default.png';

				echo <<<THEUSER
			<div class="user real">
				<div class="icon"><img src="{$avatar}" width="48" height="48" alt="{$u['name']}'s avatar" /></div>
				<div class="text">{$u[name]}</div>
			</div>
THEUSER;
			}
		?>
		<div class="clear"></div>
		</div>
	<script type="text/javascript" src="modules/admin/users2/interface.js"></script>
	<?php
	}
	/*
	function fetchList()
	Fetches the user list from the database
	Array format: $result[activated][user_num][db_type]
	*/
	function fetchList() {
		global $db,$mae;

		// Reserve the array
		$result = array();

		// Filling the results array
		for ($i=0; $i<2; $i++) {
			$q = $db->query("SELECT * FROM {$mae[db_prefix]}users WHERE activated=$i;");
			$j = 0;
			while ($r = $db->fetch_assoc($q)) {
				$result[$i][$j] = $r;
				$j++;
			}
		}

		return $result;
	}
	/*
	function fetchMerged()
	Fetches the user list without activation filtering
	Array format: $result[user_num][db_type] (inactive users first)
	*/
	function fetchMerged() {
		global $db,$mae;

		// Reserve the array
		$result = array();

		// Filling the results array
		$db->modeAssoc();
		$q = $db->query("SELECT * FROM {$mae[db_prefix]}users ORDER BY activated ASC;");
		foreach ($q as $i => $r) {
			$result[$i] = $r;
		}

		return $result;
	}
	/*
	function writeJsonInfo(array $merged)
	Writes the users info for tooltip displaying in JSON format

	NOTE: It needs the "merged" user list to work.
	*/
	function writeJsonInfo($merged) {
		global $lang;
		// Check if the argument is set
		if (!isset($merged)) die("IMPOSSIBLE ERROR :P");

		echo "<script>\nvar userInfo = [\n";
		// Iterating through the array and echoing the needed data
		$act = array($lang['users']['deactivated'], $lang['users']['activated']);
		for ($i=0; $i<count($merged); $i++) {
			echo "{";
			$u = $merged[$i];
			reset($u);
			while (list($key, $value) = each($u)) $u[$key] = addslashes($u[$key]);

			// Formatting privileges
			$privs = explode(',', $u['privileges']);
			if (!empty($privs[0])) {
				$privlist = '<ul>';
				for ($p=0; $p<count($privs); $p++) $privlist .= '<li>'.$lang['users']['priv_types'][$privs[$p]].'</li>';
				$privlist .= '</ul>';
			} else $privlist = $lang['none'];

			echo "title: '{$u[fullname]}',";
			echo "email: '<b>{$lang[users][email]}:</b> {$u[email]}',";
			echo "reg: '<b>{$lang[users][register_date]}:</b> {$u[registerdate]}',";
			echo "priv: '<b>{$lang[users][privileges]}:</b> {$privlist}',";
			echo "act: '{$act[$u[activated]]}'";
			echo "}";
			if ($i<count($merged)-1) echo ", ";
		}
		echo "];\n</script>\n";
	}

	/************************************************
	 *           ACTION HANDLING FUNCTIONS          *
	 ************************************************/

	/*
	function userEdit()
	Edits the user data, obviously
	*/
	function userEdit() {
		global $mae, $db, $lang;

		// Checking if we have an user to edit and adding slahes for the SQL query
		$user = addslashes($_GET['user']);
		if (empty($user)) echo '<h3>'.$lang['error']['error'].'</h3>'.$lang['users']['errors']['nouser'];
		else {
			// Checking if the user exists
			$db->modeAssoc();
			$q = $db->select('users', '*', array("name='$user'"));

			// Removing the slashes for general use
			$user = stripslashes($user);

			if ($db->num_rows == 0) echo '<h3>'.$lang['errortext'].'</h3>'.$lang['users']['errors']['notfound'];
			else {
				$r = $q->fields;              // Only one user with this username can exist

				reset($r);

				echo "<h3>{$lang[users][editing]}</h3>\n";

				if ($_POST['sent'] === 'true') {
					// Validation
					if (!ereg($this->email_regex, $_POST['email'])) die($lang['users']['errors']['email']);

					$p_user = trim(strip_tags(addslashes($_POST['login'])));
					$p_fullname = trim(strip_tags(addslashes($_POST['fullname'])));
					$p_email = trim(strip_tags(addslashes($_POST['email'])));
					$p_password = $_POST['password'];
					$p_privileges = (count($_POST['privileges'])==0) ? '' : implode(',', $_POST['privileges']);
					$p_activated = (empty($_POST['activated']))?0:1;

					$pass_string = empty($p_password) ? '' : ", `password`='".sha1($p_password)."'";

					// Updating the database
					$q = $db->query("UPDATE {$mae[db_prefix]}users SET `name`='$p_user', `fullname`='$p_fullname', `email`='$p_email'$pass_string, `privileges`='$p_privileges', `activated`=$p_activated WHERE `name`='$user';");

					// Hide the panel and update data
					echo $lang['users']['success']['edit'];
					echo '<script>userHide(); new Ajax(\'admin.php?action=users2\', {update: \'action_data\', evalScripts:true, onComplete: function(){updateTips();$$(\'.user\').each(function(o) {o.addEvent(\'mouseenter\', userHoverup);o.addEvent(\'mouseleave\', userHoverdown);o.addEvent(\'click\', userEdit);});}}).request();</script>';
				} else {
				// Display the form
				$os = 'this.send({update:\'mae_box_content\', evalScripts:true});return false;';
				echo <<<THEFORM
<form method="post" action="{$_SERVER[REQUEST_URI]}" onsubmit="$os">
 <input type="hidden" name="sent" value="true" />
 <table border="0" cellpadding="0" cellspacing="0">
  <tr>
   <td class="title">{$lang[users][login]}:</td>
   <td><input type="text" name="login" id="login" size="40" maxlength="20" value="$user" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][fullname]}:</td>
   <td><input type="text" name="fullname" id="fullname" size="40" maxlength="40" value="{$r[fullname]}" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][email]}:</td>
   <td><input type="text" name="email" id="email" size="40" maxlength="128" value="{$r[email]}" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][password]}:</td>
   <td><input type="password" name="password" id="password" size="40" maxlength="20" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][privileges]}:</td>
   <td>
    <select size="4" multiple="multiple" name="privileges[]" id="privileges">
THEFORM;
				$priv = array('admin', 'editing', 'modules', 'config', 'users');
				for ($i=0; $i<count($priv); $i++) {
					$s = (strpos($r['privileges'], $priv[$i])===false) ? '' : ' selected="selected"';
					echo "     <option{$s}>{$priv[$i]}</option>\n";
				}

				if ((int)$r['activated']) $ac = ' checked="checked"';
				echo <<<THEFORM
    </select> <input type="button" onclick="userClearPriv()" value="{$lang[users][clear_priv]}" />
   </td>
  </tr>
  <tr>
   <td class="title"><label for="activated">{$lang[users][activated]}:</label></td>
   <td><input type="checkbox" name="activated" id="activated"$ac /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][avatar]}:</label></td>
   <td>
THEFORM;
				$path = 'media/avatars/';
				if ((int)$r['activated']) {
					if (file_exists($path.$user.'.png')) $av = $path.$user.'.png';
					else $av = $path.'default.png';
				} else $av = $path.'inactive.png';
				echo <<<THEFORM
	<img src="$av" alt="{$lang[users][avatar]}" />
   </td>
  </tr>
 </table>
 <input type="submit" value="{$lang[save]}" />
</form>
THEFORM;
				}
			}
		}
	}

	/*
	function userAdd()
	Adds a new user
	*/
	function userAdd() {
		global $mae, $db, $lang;
		echo "<h3>{$lang[users][adding]}</h3>";

		if ($_POST['sent'] === 'true') {
			$u = addslashes($_POST['login']);
			$db->modeNum();
			$q = $db->query("SELECT COUNT(*) FROM {$mae[db_prefix]}users WHERE name='{$u}';");
			$r = $q->fields;

			// Validation
			if ($r[0] > 0) die($lang['users']['errors']['exists']);
			reset($_POST);
			while(list($key, $value) = each($_POST)) {
				$p =& $_POST[$key];
				if (empty($p)) die($lang['users']['errors']['notfilled']);
			}
			if (!ereg($this->email_regex, $_POST['email'])) die($lang['users']['errors']['email']);

			// Add the user to the database
			$user = trim(strip_tags(addslashes($_POST['login'])));
			$fullname = trim(strip_tags(addslashes($_POST['fullname'])));
			$email = trim(strip_tags(addslashes($_POST['email'])));
			$password = sha1($_POST['password']);
			$activated = ($_POST['activated']=='on')?1:0;
			$privileges = (count($_POST['privileges'])==0) ? '' : implode(',', $_POST['privileges']);
			$q = $db->query("INSERT INTO {$mae[db_prefix]}users (`name`, `fullname`, `email`, `password`, `privileges`, `registerdate`, `activated`) VALUES ('$user', '$fullname', '$email', '$password', '$privileges', NOW(), $activated);");

			// Hide the panel and update data
			echo $lang['users']['success']['add'];
			echo '<script>userHide(); new Ajax(\'admin.php?action=users2\', {update: \'action_data\', evalScripts:true, onComplete: function(){updateTips();$$(\'.user\').each(function(o) {o.addEvent(\'mouseenter\', userHoverup);o.addEvent(\'mouseleave\', userHoverdown);o.addEvent(\'click\', userEdit);});}}).request();</script>';
		} else {
			// Display the form
			$os = 'this.send({update:\'mae_box_content\', evalScripts:true});return false;';
			echo <<<THEFORM
<form method="post" action="{$_SERVER[REQUEST_URI]}" onsubmit="$os">
 <input type="hidden" name="sent" value="true" />
 <table border="0" cellpadding="0" cellspacing="0">
  <tr>
   <td class="title">{$lang[users][login]}:</td>
   <td><input type="text" name="login" id="login" size="40" maxlength="20" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][fullname]}:</td>
   <td><input type="text" name="fullname" id="fullname" size="40" maxlength="40" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][email]}:</td>
   <td><input type="text" name="email" id="email" size="40" maxlength="128" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][password]}:</td>
   <td><input type="password" name="password" id="password" size="40" maxlength="20" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][privileges]}:</td>
   <td>
    <select size="4" multiple="multiple" name="privileges[]" id="privileges">
     <option>admin</option>
     <option>editing</option>
     <option>modules</option>
     <option>config</option>
     <option>users</option>
    </select> <input type="button" onclick="userClearPriv()" value="{$lang[users][clear_priv]}" />
   </td>
  </tr>
  <tr>
   <td class="title"><label for="activated">{$lang[users][activated]}:</label></td>
   <td><input type="checkbox" name="activated" id="activated" /></td>
  </tr>
  <tr>
   <td class="title">{$lang[users][avatar]}:</label></td>
   <td><img src="media/avatars/default.png" alt="{$lang[users][avatar]}" /></td>
  </tr>
 </table>
 <input type="submit" value="{$lang[save]}" />
</form>
THEFORM;
		}
	}
	/*
	function userDelete()
	Deletes an user
	*/
	function userDelete() {
		global $db, $mae, $lang;
		echo "<h3>{$lang[users][deleting]}</h3>";

		// Show form if not sent
		$delete = $_POST['delete'];
		$confirm = $_POST['confirm'];
		if (is_array($delete)) {
			if (empty($confirm)) {
				// Show confirmation dialog

				// Writing the question and combine the query string
				echo $lang['users']['deleteconfirm'];
				for ($i=0; $i<count($delete); $i++) {
					echo $delete[$i];
					$query .= 'delete[]='.urlencode($delete[$i]);
					if ($i < count($delete)-1) {
						echo ', ';
						$query .= '&';
					}
				}
				echo '?<br />';

				// Writing the JS script for Ajax handling
				echo <<<AJAXSCRIPT
<script>
function confirmDelete(button) {
	var q = '';
	if (button===true) q = '{$query}&confirm=true';
	new Ajax('{$_SERVER['REQUEST_URI']}', {'method': 'post', 'data': q, 'update': 'mae_box_content', evalScripts: true}).request();
}
</script>
AJAXSCRIPT;

				// Writing the confirmation buttons
				echo '<input type="button" value="'.$lang['yes'].'" onclick="confirmDelete(true);" />&nbsp;';
				echo '<input type="button" value="'.$lang['no'].'" onclick="confirmDelete(false);" />';
			} else {
				// Delete the users
				for ($i=0; $i<count($delete); $i++) {
					$u = addslashes($delete[$i]);
					$q = $db->query("DELETE FROM {$mae[db_prefix]}users WHERE name='{$u}';");
				}
				echo $lang['users']['success']['delete'];
				echo '<script>userHide(); new Ajax(\'admin.php?action=users2\', {update: \'action_data\', evalScripts:true, onComplete: function(){updateTips();$$(\'.user\').each(function(o) {o.addEvent(\'mouseenter\', userHoverup);o.addEvent(\'mouseleave\', userHoverdown);o.addEvent(\'click\', userEdit);});}}).request();</script>';
			}
		} else {
			echo <<<THEFORM
<div>
 <div class="pile left" id="pile_left">
  <h4>{$lang['users']['list']}</h4>
THEFORM;
			// Displaying the user list
			$users = $this->fetchMerged();
			for ($i=0; $i<count($users); $i++) echo '  <div class="deluser">'.$users[$i]['name'].'</div>';

			echo <<<THEFORM
 </div>
 <div class="pile right" id="pile_right">
  <h4>{$lang['users']['deletelist']}</h4>
 </div>
 <div class="clear"></div>
</div>
<input type="button" value="Skasuj" onclick="deleteUsers();" />
<script>
dragMe('left');
var deletion = [];
function deleteUsers() {
	var url = '{$_SERVER['REQUEST_URI']}';
	var q = '';
	deletion.each(function(u) { q += 'delete[]='+encodeURIComponent(u)+'&'; });
	q = q.substring(0, q.length-1);

	new Ajax(url, {'method': 'post', 'data': q, 'update': 'mae_box_content', evalScripts: true}).request();
}
</script>
THEFORM;
		}
	}
}
?>
